package com.kanqiubao.kq.fragment.video;

import android.content.pm.ActivityInfo;
import android.nfc.Tag;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.dueeeke.videocontroller.StandardVideoController;
import com.dueeeke.videocontroller.component.CompleteView;
import com.dueeeke.videocontroller.component.ErrorView;
import com.dueeeke.videocontroller.component.GestureView;
import com.dueeeke.videocontroller.component.PrepareView;
import com.dueeeke.videocontroller.component.TitleView;
import com.dueeeke.videocontroller.component.VodControlView;
import com.dueeeke.videoplayer.player.VideoView;
import com.dueeeke.videoplayer.player.VideoViewManager;
import com.kanqiubao.kq.R;
import com.kanqiubao.kq.activity.video.VideoDetailActiviy;
import com.kanqiubao.kq.activity.video.VideoListActivity;
import com.kanqiubao.kq.adapter.video.VideoMainListAdapter;
import com.kanqiubao.kq.bean.video.VideoListBean;
import com.kanqiubao.kq.fragment.SmartBaseRefreshFragment;
import com.kanqiubao.kq.utils.AppConfig;
import com.kanqiubao.kq.view.tagview.TagCloudLayout;
import com.kanqiubao.kq.view.tagview.TagGroupAdapter;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

/**
 * 视频列表
 */
public class VideoListFragment extends SmartBaseRefreshFragment<VideoListBean> {

    @Override
    protected int getLayoutId() {
        return R.layout.include_smart_recycler_refresh_layout;
    }

    @Override
    protected void initData() {
        setData();
    }

    @Override
    protected void initView() {
        initVideoView();
        mSuperBaseAdapter = new VideoMainListAdapter();
        super.initView();
        mLinearLayoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(mLinearLayoutManager);
        mRecyclerView.addOnChildAttachStateChangeListener(new RecyclerView.OnChildAttachStateChangeListener() {
            @Override
            public void onChildViewAttachedToWindow(@NonNull View view) {

            }

            @Override
            public void onChildViewDetachedFromWindow(@NonNull View view) {
                FrameLayout playerContainer = view.findViewById(R.id.player_container);//释放
                if (playerContainer == null) {
                    return;
                }
                View v = playerContainer.getChildAt(0);
                if (v != null && v == mVideoView && !mVideoView.isFullScreen()) {
                    releaseVideoView();
                }
            }
        });
        mSuperBaseAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                switch (view.getId()) {
                    case R.id.video_tag1:
                        startMyActivity(VideoListActivity.class);
                        break;
                    case R.id.video_tag2:
                        startMyActivity(VideoListActivity.class);
                        break;
                    case R.id.player_container:
                        startPlay(position);
                        break;
                }

            }
        });
        if (mType == 1) {
            addHeadView();
        }
    }

    private void setData() {
        List<VideoListBean> ls = new ArrayList<>();
        VideoListBean t1 = new VideoListBean();
        t1.setFace("https://cms-bucket.nosdn.127.net/eb411c2810f04ffa8aaafc42052b233820180418095416.jpeg");
        t1.setPath("http://vfx.mtime.cn/Video/2019/02/04/mp4/190204084208765161.mp4");
        t1.setTitle("测试标题测试标题");
        ls.add(t1);
        ls.add(t1);
        ls.add(t1);
        ls.add(t1);
        ls.add(t1);
        mSuperBaseAdapter.addData(ls);
    }

    private LinearLayoutManager mLinearLayoutManager;
    protected VideoView mVideoView;
    protected StandardVideoController mController;
    protected ErrorView mErrorView;
    protected CompleteView mCompleteView;
    protected TitleView mTitleView;
    /**
     * 当前播放的位置
     */
    protected int mCurPos = -1;
    /**
     * 上次播放的位置，用于页面切回来之后恢复播放
     */
    protected int mLastPos = mCurPos;


    protected void initVideoView() {
        mVideoView = new VideoView(getActivity());
        mVideoView.setOnStateChangeListener(new VideoView.SimpleOnStateChangeListener() {
            @Override
            public void onPlayStateChanged(int playState) {
                //监听VideoViewManager释放，重置状态
                if (playState == VideoView.STATE_IDLE) {
                    AppConfig.removeViewFormParent(mVideoView);
                    mLastPos = mCurPos;
                    mCurPos = -1;
                }
            }
        });
        mController = new StandardVideoController(getActivity());
        mErrorView = new ErrorView(getActivity());
        mController.addControlComponent(mErrorView);
        mCompleteView = new CompleteView(getActivity());
        mController.addControlComponent(mCompleteView);
        mTitleView = new TitleView(getActivity());
        mController.addControlComponent(mTitleView);
        mController.addControlComponent(new VodControlView(getActivity()));
        mController.addControlComponent(new GestureView(getActivity()));
        mController.setEnableOrientation(true);
        mVideoView.setVideoController(mController);
    }

    /**
     * 开始播放
     *
     * @param position 列表位置
     */
    protected void startPlay(int position) {
        if (mCurPos == position) return;
        if (mCurPos != -1) {
            releaseVideoView();
        }
        VideoListBean videoBean = mSuperBaseAdapter.getItem(position);
        //边播边存
//        String proxyUrl = ProxyVideoCacheManager.getProxy(getActivity()).getProxyUrl(videoBean.getUrl());
//        mVideoView.setUrl(proxyUrl);

        mVideoView.setUrl(videoBean.getPath());
        mTitleView.setTitle(videoBean.getTitle());
        View itemView;
        if (mType == 1) {
            itemView = mLinearLayoutManager.findViewByPosition(position + 1);
        } else {
            itemView = mLinearLayoutManager.findViewByPosition(position);
        }

        if (itemView == null) return;
        PrepareView pv = itemView.findViewById(R.id.prepare_view);
        FrameLayout con = itemView.findViewById(R.id.player_container);
//        VideoRecyclerViewAdapter.VideoHolder viewHolder = (VideoRecyclerViewAdapter.VideoHolder) itemView.getTag();
        //把列表中预置的PrepareView添加到控制器中，注意isPrivate此处只能为true。
        mController.addControlComponent(pv, true);
        AppConfig.removeViewFormParent(mVideoView);
        con.addView(mVideoView, 0);
        //播放之前将VideoView添加到VideoViewManager以便在别的页面也能操作它
        VideoViewManager.instance().add(mVideoView, "list");
        mVideoView.start();
        mCurPos = position;

    }

    private void releaseVideoView() {
        mVideoView.release();
        if (mVideoView.isFullScreen()) {
            mVideoView.stopFullScreen();
        }
        if (getActivity().getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
            getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
        mCurPos = -1;
    }

    @Override
    public void onPause() {
        super.onPause();
        pause();
    }

    @Override
    public void onResume() {
        super.onResume();
//        resume();
    }

    /**
     * 由于onPause必须调用super。故增加此方法，
     * 子类将会重写此方法，改变onPause的逻辑
     */
    protected void pause() {
        releaseVideoView();
    }

    /**
     * 由于onResume必须调用super。故增加此方法，
     * 子类将会重写此方法，改变onResume的逻辑
     */
    protected void resume() {
        if (mLastPos == -1)
            return;
//        if (MainActivity.mCurrentIndex != 1)
//            return;
        //恢复上次播放的位置
        startPlay(mLastPos);
    }

    TagCloudLayout mTagCloudLayout;
    TagGroupAdapter mTagGroupAdapter;

    /**
     * 添加详细的头部
     */
    private void addHeadView() {
        View v = LayoutInflater.from(getActivity()).inflate(R.layout.video_detail_head_layout, null);
        mTagCloudLayout = v.findViewById(R.id.tag_id);
        List<String> ls = new ArrayList<>();
        ls.add("标签标签标签");
        ls.add("标签标签111");
        mTagGroupAdapter = new TagGroupAdapter(getActivity(), ls);
        mTagCloudLayout.setAdapter(mTagGroupAdapter);
        mSuperBaseAdapter.addHeaderView(v);
    }

    @Override
    public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        startMyActivity(VideoDetailActiviy.class);
        super.onItemClick(adapter, view, position);
    }
}
